package mediator
{
	import data.ToneGate;
	
	import events.ClockEvent;
	import events.TempoPanelEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	
	import gui.Chassis;
	import gui.panel.OutputControls;

	public class ChassisMediator extends EventDispatcher
	{
		private var _chassis:Chassis;
		
		public function ChassisMediator(target:IEventDispatcher=null)
		{
			super(target);
		}
		
		public function register():void
		{
			chassis.tempoPanel.addEventListener( TempoPanelEvent.VALUE_CHANGED, handleTempoChanged );
			chassis.clock.addEventListener( ClockEvent.CLOCK_TICK, handleClockTick );
			chassis.outputControls.addEventListener( OutputControls.CLICK_CONNECT, handleClickConnect );
			chassis.output.addEventListener( Event.CONNECT, handleOutputConnect );
			chassis.output.addEventListener( IOErrorEvent.IO_ERROR, handleOutputError );
			chassis.tempoPanel.requestValues();
		}
		
		protected function handleTempoChanged( event:TempoPanelEvent ):void
		{
			chassis.clock.tempo = event.getValue();
		}
		
		protected function handleClockTick( event:ClockEvent ):void
		{
			var step:int = event.getStep();
			var stepState:Boolean = chassis.stepButtons.getButtonState( step );
			var gate:int = chassis.gateButtons.getGateState( step ) ? 1 : 0;
			var tone:Number = 0;
			var outData:ToneGate = new ToneGate();
		
			if( stepState )
			{
				tone = chassis.toneKnobPanel.getTone( step ) as Number;
				tone = Math.round( tone );
			}
			
			outData.tone = tone;
			outData.gate = gate;
			chassis.output.sendToOutput( outData );
			chassis.stepButtonLeds.turnOnLed = step;
		}
		
		protected function handleClickConnect( e:Event ):void
		{
			chassis.output.connect();
		}
		
		protected function handleOutputConnect( e:Event ):void
		{
			chassis.outputControls.led1.state = true;
		}
		
		protected function handleOutputError( e:IOErrorEvent ):void
		{
			chassis.outputControls.led1.blink( 3 );
		}
		
		public function set chassis( value:Chassis ):void
		{
			_chassis = value;
		}
		
		public function get chassis( ):Chassis
		{
			return _chassis;
		}
		
		
	}
}